import { data } from 'jquery';
//tslint:disable
import { ModalOfEditMoreInfoComponent } from './../post-edit-form/modal-of-edit-more-info/modal-of-edit-more-info.component';
import { ChooseDepartmentComponent } from './../choose-department/choose-department.component';
import { ModalOfMultipleComponent } from './../post-edit-form/modal-of-multiple/modal-of-multiple.component';
import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

import { Platform, ModalController, NavParams } from '@ionic/angular';
import { isArray, isObject, isBoolean, isNullOrUndefined } from 'util';
import { ActionSheetService } from 'ng-zorro-antd-mobile';
import { ChooseCityComponent } from '../choose-city/choose-city.component';
import { AppGlobalService } from '../../shared/service/app-global.service';
import { HttpService } from '../../shared/service/http.service';
import { PublishHouseTypeComponent } from '../publish-house-type/publish-house-type.component';
import { ModalMultipleSelect3Component } from '../post-edit-form/modal-multiple-select3/modal-multiple-select3.component';
declare var $;
@Component({
  selector: 'app-search-filter',
  templateUrl: './search-filter.component.html',
  styleUrls: ['../post-and-eitor/post-and-eitor.component.scss','./search-filter.component.scss']
})
export class SearchFilterComponent implements OnInit {
  @Input() tagData: any;
  @Input() pageParams: any;
  @Input() result: any;
  private timer: any;
  titleBar: any;
  dataList: any;
  formGroup: FormGroup = new FormGroup({});
  formFilter: FormGroup = new FormGroup({});
  formOrder: FormGroup = new FormGroup({});
  data: any;
  allLabel: any = {};
  positionInfo: any;
  submitButtonId: any;
  searchArray: any = {
    industry: '', // 行业
    district: '', // 区域
    order: '' // 排序
  };
  aheight: any;
  isNative: any = false;
  keyboardShow: any;
  orderDefault: any;
  ifbutton: any;
  buttonstyle: any;
  buttonslink: any; // 当需要跳page时声明的赋值对象
  resetButton: any; // 重置按钮
  houseTypeShowValue = '不限';
  roomType = '1';
  roomHall = '1';
  roomBit = '1';
  @ViewChild('searchBar') searchBar;
  constructor(
    private http: HttpService,
    private appGlobalService: AppGlobalService,
    private platform: Platform,
    private actionSheet: ActionSheetService, // 必须有
    // private tabService: TabsService,
    // private eventService: EventService,
    private modalCtrl: ModalController,

  ) {
    window.addEventListener('keyboardWillShow', () => {
      this.keyboardShow = true;
      console.log("keyboardWillShow!!!!!")
    });
    window.addEventListener('keyboardWillHide', () => {

      this.searchBar.getInputElement().then((input) => {
        input.blur();
        console.log("input.blur()!!!!!")
      });
      console.log("keyboardWillHide!!!!!")
    });
    window.addEventListener('keyboardDidHide', () => {
      this.keyboardShow = false;
      console.log("keyboardDidHide!!!!!")
      this.searchBar.getInputElement().then((input) => {
        input.blur();
        console.log("input.blur()!!!!!")
      });
    });
  }

  ngOnInit() {
    if (this.platform.is('cordova')) {
      this.isNative = true;
    } else {
      this.isNative = false;
    }
    this.positionInfo = JSON.parse(localStorage.getItem('position'));
    // 是模态窗方式打开
    if (this.pageParams) {
      this.http.post('application/page', this.pageParams, res => {
        this.tagData = JSON.parse(res.script).views[0].tags[0];
        this.titleBar = JSON.parse(res.script).titleBar;
        this.data = this.tagData.data;
        // 判断是否有条件显示的子项
        this.data.data.formObj.forEach(element => {
          if (element.type) {
            if (element.type === 'singleColumnPicker' &&
              element.subData &&
              element.subData.length > 0) {
              element.subData.forEach(el => {
                if (el.showCondition && el.showCondition === element.data[0].value) {
                  if (el.index && el.index < this.data.data.formObj.length) {
                    this.data.data.formObj.splice(el.index, 0, el);
                  } else if (el.index && el.index > this.data.data.formObj.length) {
                    this.data.data.formObj.push(el);
                  }
                }
              });
            }
          }
        });

        this.createControl();
        this.platform.ready().then((readySource) => {
          console.log('Width: ' + this.platform.width());
          console.log('Height: ' + this.platform.height());
          this.aheight = this.platform.height() * 0.8;
        });
      });
    } else {
      this.data = this.tagData.data;
      // 判断是否有条件显示的子项
      this.data.data.formObj.forEach(element => {
        if (element.type) {
          switch (element.type) {
            case 'singleColumnPicker':
              if (element.type === 'singleColumnPicker' &&
                element.subData &&
                element.subData.length > 0) {
                element.subData.forEach(el => {
                  if (el.showCondition && el.showCondition === element.data[0].value) {
                    if (el.index && el.index < this.data.data.formObj.length) {
                      this.data.data.formObj.splice(el.index, 0, el);
                    } else if (el.index && el.index > this.data.data.formObj.length) {
                      this.data.data.formObj.push(el);
                    }
                  }
                });
              }
              break;
            case 'modalMultipleSelect3_Auto':
              {
                if (element.data && element.data.length > 0) {
                  element['children'] = element.data;
                }
              }
              break;
            case 'switchButtonFW_3': {
              element['multiSelect'] = true;
              element['itemList'] = element.data;
            }
              break;

            default:
              break;
          }

        }
      });

      this.createControl();
      this.platform.ready().then((readySource) => {
        console.log('Width: ' + this.platform.width());
        console.log('Height: ' + this.platform.height());
        this.aheight = this.platform.height() * 0.8;
      });
    }
    this.tagData.data.data.formObj.forEach(element => {
      if (element.submitButton) {
        if (element.submitButton.cssStyle) {
          this.ifbutton = true;
          this.buttonslink = element.submitButton;
          if (element.submitButton.cssStyle === 'recommend') {
            this.buttonstyle = true;
          } else {
            this.buttonstyle = false;
          }
        } else {
          this.ifbutton = false;
        }
      } else if (element.resetButton) {
        this.resetButton = element.resetButton;
      }
      if (element.type === "dateInput") {
        if (element.itemList[0] && element.itemList[1]) {
          element.itemList[0].disable = false;
          element.itemList[1].disable = true;
        }
      }
    });

  }
  /*
  {
                                      "type":"doubleInput",
                                      "formKey":"opportunity_area",
                                      "label":"面积",
                                      "parent":"filter",
                                      "needFormKey":true,
                                      "hasManyField":false,
                                      "useChildName":true, // 使用子项中的name 作为字段名字
                                      "endLabel":"平米",
                                      "itemList":[
                                          {
                                              "formKey":"int",
                                              "max":"99999",
                                              "name":"min_opportunity_area",
                                              "needMax":true,  // , 拼接
                                              "placeHolder":"最小",
                                              "maxLength":"6"
                                          },
                                          {
                                              "formKey":"int",
                                              "name":"max_opportunity_area",
                                              "needMax":false,
                                              "placeHolder":"最大",
                                              "maxLength":"6"
                                          }
                                      ]
                                  },
  */
  createControl() {
    const that = this;

    this.data.data.formObj.forEach(element => {
      if (element.type) {
        if (element.type === 'citySelect') {

          if (!that.formGroup.controls[element.formKey]) {
            if (element.value && element.showValue) {
              that.formGroup.addControl(element.formKey, new FormControl(element.value, []));
            } else {
              const city = JSON.parse(localStorage.getItem('position')).code;
              element.showValue = JSON.parse(localStorage.getItem('position')).name;
              that.formGroup.addControl(element.formKey, new FormControl(city, []));
            }
            
          }
        } else if (element.type === 'departmentSelect') {

          if (!that.formGroup.controls[element.formKey]) {
            that.formGroup.addControl(element.formKey, new FormControl('', []));
          }
        } else if (element.type === 'modalMultipleSelect') {

          if (!that.formGroup.controls[element.formKey]) {
            element.showValue = isNullOrUndefined(element.showValue) ? '' : element.showValue; 
            that.formGroup.addControl(element.formKey, new FormControl('', []));
          }

          if (element.submit) {
            element.data = [];
            this.getIndustryData(element);
          }  
        } else if (element.type === 'modalMultipleFormKeySelect') {
          this.houseTypeShowValue = '不限';
          // 初始化默认参数
          that.formGroup.addControl(element.formKey, new FormControl(''));

          for (let index = 0; index < element.subData.length; index++) {
            const subElement = element.subData[index];
            that.formGroup.addControl(subElement.formKey, new FormControl(''));
          }

        } else if (element.type === 'doubleInput' && element.useChildName) {


          for (let i = 0; i < element.itemList.length; i++) {
            if (element.itemList[i].name && element.itemList[i].name.length > 0) {

              if (!that.formGroup.controls[element.itemList[i].name]) {

                that.formGroup.addControl(element.itemList[i].name, new FormControl('', [Validators.maxLength(element.itemList[i].maxLength)]));
                this.allLabel[element.itemList[i].name] = { label: `${element.itemList[i].placeHolder}${element.label}` };
                element.itemList[i].value = "";
              }


            }
          }
        } else if (element.type === 'doubleInput') {
          for (let i = 0; i < element.itemList.length; i++) {

            if (!that.formGroup.controls[`cus_${i}${element.formKey}`]) {
              that.formGroup.addControl(`cus_${i}${element.formKey}`, new FormControl('', [Validators.maxLength(element.itemList[i].maxLength)]));
              this.allLabel[`cus_${i}${element.formKey}`] = { label: `${element.itemList[i].placeHolder}${element.label}` };
              element.itemList[i].value = "";
            }


          }

        } else if (element.type === 'doubleColumnPicker' || element.type === 'singleColumnPicker') {
          if (element.parent !== 'order') {
            if (!that.formGroup.controls[element.formKey]) {
              that.formGroup.addControl(element.formKey, new FormControl('', [Validators.maxLength(element.maxLength)]));
              this.allLabel[element.formKey] = { label: element.label };
              if (element.id) {
                element.checkLabel = element.placeHolder;

                this.getDropDownData(element);
              } else {
                element.checkLabel = element.data[0].label ? element.data[0].label : element.placeHolder;
              }
              element.value = "";
            }

          } else {
            if (!that.formGroup.controls[`order_${element.formKey}`]) {
              that.formGroup.addControl(`order_${element.formKey}`, new FormControl(''));
              this.orderDefault = element.value;
              element.checkLabel = element.placeHolder;
              element.value = "";
            }
          }

        } else if (element.type === 'singleCheckBox') {
          for (let i = 0; i < element.itemList.length; i++) {
            if (!that.formGroup.controls[element.itemList[i].formKey]) {
              that.formGroup.addControl(element.itemList[i].formKey, new FormControl('', []));
            }
          }
        } else if (element.type === 'multipleSelect3') {
          that.formGroup.addControl(element.formKey, new FormControl('', []));
          element.value = [];
          element.formType = "multipleSelect3";
          element.label = "请选择您需要代理的商品(可多选)";
          element.formKey = element.formKey;
          element.children = element.data;
          element.children[0].open = true;
          element.current = element.children[0];
          // current 为第一个参数。
          console.log('data,', element);
        } else {
          if (!that.formGroup.controls[element.formKey]) {
            that.formGroup.addControl(element.formKey, new FormControl('', [Validators.maxLength(element.maxLength)]));
            this.allLabel[element.formKey] = { label: element.label };
            element.value = "";
          }


        }
        if (element.type === 'doubleInput' && element.subData && element.subData.length === 1){
          if (!that.formGroup.controls[element.subData[0].formKey]) {
            that.formGroup.addControl(element.subData[0].formKey, new FormControl(element.subData[0].data[0].value, []));
            element.subData[0].showValue = element.subData[0].data[0].value;
          }
        }
      } else if (element.submitButton) {
        this.submitButtonId = element.submitButton.id;
      }
    });
    // console.log(this.data.data.formObj, 'dadttttt', this.formGroup, 'ggggggg');
  }


  resetShowValue() {
    const that = this;
    this.data.data.formObj.forEach(element => {
      if (element.type) {
        if (element.type === 'citySelect'
          || element.type === 'departmentSelect'
          || element.type === 'modalMultipleSelect'
          || element.type === 'modalMultipleFormKeySelect'
          || element.type === 'switchButtonFW_3'
          || element.type === 'modalMultipleSelect3_Auto'
          || element.type === 'modalOfMoreItems') {
          element.showValue = element.placeHolder;
        } else if (element.type === 'modalMultipleFormKeySelect') {
          this.houseTypeShowValue = '不限';
        } else if (element.type === 'doubleInput' && element.useChildName) {
          for (let i = 0; i < element.itemList.length; i++) {
            if (element.itemList[i].name && element.itemList[i].name.length > 0) {
              this.allLabel[element.itemList[i].name] = { label: `${element.itemList[i].placeHolder}${element.label}` };
              element.itemList[i].value = "";
            }
          }
        } else if (element.type === 'doubleInput') {
          for (let i = 0; i < element.itemList.length; i++) {
            this.allLabel[`cus_${i}${element.formKey}`] = { label: `${element.itemList[i].placeHolder}${element.label}` };
            element.itemList[i].value = "";
          }
          if (element.subData && element.subData.length === 1){
            element.subData[0].showValue = element.subData[0].data[0].value;
          }
        } else if (element.type === 'doubleColumnPicker' || element.type === 'singleColumnPicker') {
          if (element.parent !== 'order') {
            this.allLabel[element.formKey] = { label: element.label };
            if (element.id) {
              element.checkLabel = element.placeHolder;
              this.getDropDownData(element);
            } else {
              element.checkLabel = element.data[0].label ? element.data[0].label : element.placeHolder;
            }
            element.value = "";
          } else {
            this.orderDefault = element.value;
            element.checkLabel = element.placeHolder;
            element.value = "";
          }
        } else if (element.type === 'singleCheckBox') {

          for (let i = 0; i < element.itemList.length; i++) {
            if (!that.formGroup.controls[element.itemList[i].formKey]) {
              that.formGroup.addControl(element.itemList[i].formKey, new FormControl('', []));
            }
          }
        } else if (element.type === "dateInput") {
          if (element.itemList[0].value) {
            element.itemList[0].value = "";
          }
          if (element.itemList[1].value) {
            element.itemList[1].value = "";
          }
        } else if (element.type === 'multipleSelect3') {
          this.clearCheckBtn(element.children);
        } else {
          this.allLabel[element.formKey] = { label: element.label };
          element.value = "";
        }
      }
    });
  }

  getDropDownData(item) {
    const city = JSON.parse(localStorage.getItem('position')).code;
    const table = {
      code: city
    };
    const params = {
      content: table,
      id: item.id,
      sessionId: localStorage.getItem('sessionId')
    };
    // 请求获取新数据
    this.http.post('application/submit', params, res => {
      // 请求数据成功
      if (res.data.items) {
        item.data = res.data.items;
        this.getPickerLabel(item);
      } else {
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, 'middle');
        this.getPickerLabel(item);
      }
    });
  }
  onOk1(result, item) { // 排序
    const that = this;
    if (result && result.length && isArray(result)) {
      item.checkLabel = `${result[0].label}`;
      // 有需要根据条件显示的选项
      if (item.subData && item.subData.length > 0) {

        item.subData.forEach(el => {
          if (el.showCondition && el.showCondition === result[0].value) {
            if (el.index && el.index < this.data.data.formObj.length) {
              if (this.data.data.formObj[el.index].index && this.data.data.formObj[el.index].index == el.index) {
                // 替换
                that.formGroup.removeControl(el.formKey)
                delete this.allLabel[el.formKey];
                this.data.data.formObj.splice(el.index, 1, el);
                this.createControl();

              } else {
                // 增加
                this.data.data.formObj.splice(el.index, 0, el);
                this.createControl();

              }

            } else if (el.index && el.index > this.data.data.formObj.length) {

              this.data.data.formObj.push(el);
              this.createControl();

            }
          }
        });

      }

      this.searchArray.order = item.checkLabel;
      // needFormKey为false，分割code 传参格式变为：
      //  "filter":{
      // "contract_service_status":"2",
      // "contract_customer_status":"!0"
      // }
      if (item.needFormKey) {
        // needFormKey为true，保持原样
        if (item.hasManyField) {
          const arr = String(result[0].code).split(";");
          const obj = {};
          arr.forEach(element => {
            const z = element.split('=');
            obj[z[0]] = z[1];
          });
          item.value = obj;
        } else {
          item.value = result[0].code;
        }
      } else {
        const arr = String(result[0].code).split(";");
        const obj = {};
        arr.forEach(element => {
          const z = element.split(':');
          obj[z[0]] = z[1];
        });
        item.value = obj;
        console.log(item.value);
      }
    }
  }
  onOk2(result, item) { // 行业 区域
    if (result && result.length && isArray(result)) {



      if (result.length === 1) {
        item.value = result[0].code;
        item.checkLabel = `${result[0].label}`;
        if (item.formKey === 'opportunity_industry_id') {
          this.searchArray.industry = item.checkLabel;
        }
        if (item.formKey === 'opportunity_district_id') {
          this.searchArray.district = item.checkLabel;
        }
      } else {
        item.value = result[1].code;
        item.checkLabel = `${result[0].label} ${result[1].label}`;
        if (item.formKey === 'opportunity_industry_id' && result[1].code !== result[0].code) {
          this.searchArray.industry = result[1].label;
        }
        if (item.formKey === 'opportunity_industry_id' && result[1].code === result[0].code) {
          this.searchArray.industry = result[0].label;
        }
        if (item.formKey === 'opportunity_district_id') {
          this.searchArray.district = result[1].label;
        }
      }

      // 2024.04.26 新增参数联调
      if (item.name) {
        if (this.appGlobalService[item.name] && this.appGlobalService[item.name] === item.formKey) {
          if (item.value && item.value.length >= 2) {
            this.appGlobalService[item.formKey] = item.value.substring(0, 2);
          }
        }
      }
    }
  }

  getPickerLabel(item) {
    if (item.value) {
      item.data.forEach(element => {
        if (!element.children || !element.children.length) {
          if (element.code === item.value) {
            item.checkLabel = element.label;
          }
        } else {
          element.children.forEach(ele => {
            if (ele.code === item.value) {
              item.checkLabel = element.label + ' ' + ele.label;
            }
          });
        }
        if (!item.checkLabel) {
          item.checkLabel = item.data[0].label;
        }
      });
    } else {
      item.checkLabel = item.data[0].label;
    }
  }

  changeValue(event, item) {
    if (event.detail.value.length > Number(item.maxLength)) {
      item.value = event.detail.value.slice(0, Number(item.maxLength));
      this.formGroup.patchValue({ [item.formKey]: item.value });
    }
  }

  onChange(item, value) {
    if (value) {
      this.formGroup.patchValue({ [item.formKey]: item.value });
    } else {
      delete this.formGroup.value[item.formKey];
    }
    console.log(this.formGroup.value, 'vvvvvvvvvvvv');
  }

  goBack() {
    if (this.formGroup.invalid) {
      this.getErrors(this.formGroup);
      return;
    }
  }
  getErrors(form) {
    const errs = [];
    for (const name in form.controls) {
      if (form.controls[name].errors) {
        errs.push({ key: [name], err: form.controls[name].errors });
      }
    }
    if (errs.length) {
      const name = errs[0];
      if (name.err.required !== undefined) {
        this.appGlobalService.showToast(`请输入${this.allLabel[name.key]}`, 3000, 'top');
      } else if (name.err.pattern !== undefined) {
        this.appGlobalService.showToast(`${this.allLabel[name.key]}数据输入不正确`, 3000, 'top');
      }
    }
  }

  reset() {
    // this.createControl();
    this.formGroup.reset();
    this.resetShowValue();
  }

  noValue(curValue) {
    if (curValue === undefined || curValue === "" || JSON.stringify(curValue) === '{}') {
      return true;
    }
  }
  searchEvent(event?) {
    let checkValid = true;
    let transferParamsFromModal = false;
    this.tagData.data.data.formObj.forEach(element => {
      console.log('msg--->:' + element.type);
      if (element.type === "dateInput") {
        // 比较日期顺序之后存入formgrop
        if (element.itemList[0].value && element.itemList[1].value) {
          /* if (this.contrast(element.itemList[1].value, element.itemList[0].value) === true) {
            this.appGlobalService.showToast('结束时间不能小于开始时间', 2000, 'middle');
            return;
          } else { */
          /* const datetfield = element.itemList[0].value + ' 00:00:00' + ',' + element.itemList[1].value + ' 00:00:00'; */
          const datetfield = element.itemList[0].value + ',' + element.itemList[1].value;
          this.formGroup.patchValue({ [element.formKey]: datetfield });
          /* } */
        }
      } else if (element.type === 'multipleSelect3') {
        checkValid = false;
        const modal = this.modalCtrl.getTop();
        if (modal) {
          transferParamsFromModal = true;
        } else {
          transferParamsFromModal = false;
        }
      }
    });
    if (event && event.keyCode !== 13) {
      return;
    }
    console.log(this.formGroup);
    let params: any = {
      filter: {},
      order: {
        sort: {}
      }
    };

    if (checkValid && this.formGroup.invalid) {
      this.getErrors(this.formGroup);
      return;
    }

    this.tagData.data.data.formObj.forEach(element => {
      if (element.type === 'doubleInput' && element.useChildName) {
        if (element.itemList[0].value) {
          let name = element.itemList[0].name;
          let value;
          if (element.itemList[0].needMax) {
            value = element.itemList[0].value + ',' + (element.itemList[0].max ? element.itemList[0].max : '');
          } else {
            value = '0,' + element.itemList[0].value;
          }
          if (element.parent === 'params') {
            params[name] = value;
          }
        }
        if (element.itemList[1].value) {
          let name = element.itemList[1].name;
          let value;
          if (element.itemList[1].needMax) {
            value = element.itemList[1].value + ',' + element.itemList[1].max ? element.itemList[1].max : '';
          } else {
            value = '0,' + element.itemList[1].value;
          }
          if (element.parent === 'params') {
            params[name] = value;
          }
        }

      } else if (element.type === 'doubleInput' && element.parent === 'params') {
          const key = element.formKey;
          const key0 = "cus_0"+element.formKey;
          const key1 = "cus_1"+element.formKey;
          if (!this.formGroup.value[key1] && !this.formGroup.value[key0]) {
            delete this.formGroup.value[key];
            delete this.formGroup.value[key0];
          } else if (this.formGroup.value[key1] && Number(this.formGroup.value[key1]) <= Number(this.formGroup.value[key0])) {
            this.appGlobalService.showToast(`${this.allLabel[key1].label}不能小于等于${this.allLabel[key0].label}`, 3000, 'top');
            return;
          } else {
            if (!this.formGroup.value[key0]) {
              this.formGroup.value[key0] = '';
            }
            if (!this.formGroup.value[key1]) {
              this.formGroup.value[key1] = '';
            }
            const value = `${this.formGroup.value[key0]},${this.formGroup.value[key1]}`;
            this.formGroup.addControl(element.formKey, new FormControl(value));

            // this.formGroup.patchValue({ [element.formKey]: value });

            delete this.formGroup.value[key0];
            delete this.formGroup.value[key1];
          }
        }
      if (element.parent === 'params') {
        params[element.formKey] = this.formGroup.value[element.formKey];
        // delete this.formGroup.value[element.formKey];

      }
      if (element.type === 'doubleInput' && element.subData && element.subData.length === 1){
        if (element.subData[0].parent === 'params') {
          params[element.subData[0].formKey] = this.formGroup.value[element.subData[0].formKey];
        }
      }
    });
    // console.log(this.formGroup);

    for (const item in this.formGroup.value) {
      if (!this.formGroup.value[item]) {
        delete this.formGroup.value[item];
      }
      if (item.indexOf('order_') === 0) {
        let value = [];
        if (this.formGroup.value[item]) {
          value = this.formGroup.value[item].split(";");
        }
        // else{
        //   value = this.orderDefault.split(";")
        // }
        value.forEach(element => {
          const arr = element.split(":");
          params.order.sort[arr[0]] = arr[1];
        });
        delete this.formGroup.value[item];
      } else {
        if (item.indexOf('cus_0') > -1) {
          const key = item.slice(5);
          const key1 = `cus_1${key}`;
          if (!this.formGroup.value[key1] && !this.formGroup.value[item]) {
            delete this.formGroup.value[key];
            delete this.formGroup.value[item];
          } else if (this.formGroup.value[key1] && Number(this.formGroup.value[key1]) <= Number(this.formGroup.value[item])) {
            this.appGlobalService.showToast(`${this.allLabel[key1].label}不能小于等于${this.allLabel[item].label}`, 3000, 'top');
            return;
          } else {
            if (!this.formGroup.value[item]) {
              this.formGroup.value[item] = '';
            }
            if (!this.formGroup.value[key1]) {
              this.formGroup.value[key1] = '';
            }
            params.filter[key] = `${this.formGroup.value[item]},${this.formGroup.value[key1]}`;
            delete this.formGroup.value[item];
            delete this.formGroup.value[key1];
          }
        } else {
          // needFormKey为false，this.formGroup.value[item]转为对象，传参格式变更
          if ($.isPlainObject(this.formGroup.value[item]) && params.filter === {}) {
            params.filter = this.formGroup.value[item];
          } else {
            console.log(this.formGroup.value);
            if (this.formGroup.value[item]) {
              const r = new RegExp("^[1-2]\\d{3}-(0?[1-9]||1[0-2])-(0?[1-9]||[1-2][1-9]||3[0-1])$");
              if (typeof (this.formGroup.value[item]) === 'string' && r.test(this.formGroup.value[item].split(",")[0]) === true && r.test(this.formGroup.value[item].split(",")[0]) === true) {
                if (this.contrast(this.formGroup.value[item].split(",")[1], this.formGroup.value[item].split(",")[0]) === true) {
                  this.appGlobalService.showToast('结束时间不能小于开始时间', 2000, 'middle');
                  return;
                } else {

                  params.filter[item] = this.formGroup.value[item].split(",")[0] + ' 00:00:00' + ',' + this.formGroup.value[item].split(",")[1] + ' 23:59:59';
                }
              } else {
                if ($.isPlainObject(this.formGroup.value[item])) {
                  params.filter[item] = Object.values(this.formGroup.value[item])[0];
                } else {
                  params.filter[item] = this.formGroup.value[item];
                }
              }
            }
          }
        }
      }
    }
    const values1 = Object.values(params.filter);
    const values2 = Object.values(params.order);
    const a = values1.every(this.noValue);
    const b = values2.every(this.noValue);
    if (a && b) {
      // this.appGlobalService.showToast('请输入搜索条件', 3000, 'top');
      console.log('条件为空，改为搜索全部效果');
      // return;
    }
    // 删除与params相key 的filter参数
    Object.keys(params).forEach(element => {
      Object.keys(params.filter).forEach(e => {
        if (element === e) {
          delete params.filter[e];
        }
      });
    });
    // 如果是模态
    if (transferParamsFromModal) {
      this.modalCtrl.dismiss(params);
      return;
    }
    if (this.pageParams) {

      for (const a in params.filter) {
        this.result.filter[a] = params.filter[a];
      }

      for (const a in params.order) {
        this.result.order[a] = params.order[a];
      }
      this.modalCtrl.dismiss(this.result);

      return;
    }
    // if(values2.every(this.noValue)){
    //     let value = this.orderDefault.split(";");
    //     value.forEach(element => {
    //       const arr = element.split(":");
    //       params.order.sort[arr[0]] = arr[1];
    //     });
    // }

    let curPageId;

    if (this.buttonstyle === true) {
      curPageId = this.buttonslink.link.target;
      params = Object.assign(params, this.buttonslink.link.params);
      const filter = {
        params,
        pageId: curPageId,
        sessionId: localStorage.getItem('sessionId')
      };
      console.log(JSON.stringify(filter));
      this.appGlobalService.goToForward(filter);
    } else {

      this.appGlobalService.popTarget();
      let curPageParams;
      let curTarget = this.appGlobalService.getCurrentTarget();
      if (curTarget && curTarget.params) {
        curPageParams = curTarget.params;
        curPageId = curTarget.pageId;
        params = Object.assign(params, curPageParams);
      }

      // 新增支持buttonsLink配置
      if (this.buttonslink && this.buttonslink.link.params) {
        params = Object.assign(params, this.buttonslink.params);
      }

      // 蜂喔商户2.1.0 销售中土特管理tab切换指定选中
      if (params && params.needCheckAndReplaceIndexTab !== undefined) {
        if (this.appGlobalService[params.needCheckAndReplaceIndexTab] !== undefined && params.indexTab !== undefined) {
          params.indexTab = this.appGlobalService[params.needCheckAndReplaceIndexTab];
        }
      }
      const filter = {
        params,
        pageId: curPageId,
        sessionId: localStorage.getItem('sessionId')
      };


      const showName = sessionStorage.getItem('showName');
      filter.params.showName = showName;
      // localStorage.setItem('searchParams', JSON.stringify(filter));
      /* 与产品沟通，案例筛选里面的进行的任何条件都不会影响到上个页面的选择条件 */
      /*  localStorage.setItem('searchArray', JSON.stringify(this.searchArray)); */
      // return;
      this.http.post('application/page', filter, res => {
        if (res) {
          // 2024.01.22 imagsTag需要特殊处理下
          if (res.script) {
            const pageData = JSON.parse(res.script);
            if (pageData
              && pageData.views
              && pageData.views.length > 0
              && pageData.views[0].tags[0]
              && pageData.views[0].tags[0].name === 'imagesTag'
              && pageData.views[0].tags[0].currentData.tags
              && pageData.views[0].tags[0].currentData.tags.length > 0
              && pageData.views[0].tags[0].currentData.tags[0].name === 'switchBlockTag'
              && pageData.views[0].tags[0].currentData.tags[1]
              && pageData.views[0].tags[0].currentData.tags[1].style === 'singleManageListTag'
              && pageData.views[0].tags[0].currentData.tags[1].name.indexOf('enableSearchUpdateTagData') > -1
            ) {
              const tempTagData = pageData.views[0].tags[0].currentData.tags[1];

              if (tempTagData.data && tempTagData.data.submit && tempTagData.data.submit.content) {
                if (filter.params.filter) {
                  tempTagData.data.submit.content['filter'] = filter.params.filter;
                }
                if (filter.params.order) {
                  tempTagData.data.submit.content['order'] = filter.params.order;
                }
              }
              this.appGlobalService.eventService.eventEmit.emit(tempTagData.name, tempTagData);
              console.log('updateSearchTag...');
              localStorage.removeItem('needRefresh');
              this.appGlobalService.goBack();
            } else {
              this.appGlobalService.refreshPageData(res, true);
            }
          }
        }
      });
    }
  }




  cancel() {

  }
  async getIndustryData(item) {
    let params = {}
    // 行业 区域通用化
    if (item.submit) {
      params = {
        content: item.submit.params,
        id:  item.submit.id ,
        sessionId: localStorage.getItem('sessionId')
      };
    } else {
        params = {
        content: { type: 'city' },
        id: item.submit.id,
        sessionId: localStorage.getItem('sessionId')
      };
    }
    
    // 请求获取新数据
    await this.http.post('application/submit', params, res => {
      // 请求数据成功 重置区域数据
      if (res.data.data) {
        item.data = res.data.data;
      } else {
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    });
  }

  // 打开行业模态框 // 多选全国区域
  async modalMultipleSelect(item) {
    item['formType'] = item.type+"LJBOTTOM"; // 修改为底部弹窗半屏
    const that = this;
    const modal = await this.modalCtrl.create({
      component: ModalOfMultipleComponent,
      componentProps: { data: item },
      cssClass: 'bottom-modal',
    });
    modal.onDidDismiss().then(function (data) {
      if (data.data) {
        const selectedData = data.data;
        const selectedLabel = selectedData.map(v => {
          return v.label;
        });
        const selectedValue = selectedData.map(v => {
          return v.value;
        });
        if (data.data.length) {
          that.formGroup.patchValue({ [item.formKey]: selectedValue.join(',') });
          item.value = selectedValue;
          item.showValue = selectedLabel;
        } else {
          that.formGroup.patchValue({ [item.formKey]: '' });
          item.value = '';
        }
      }
    });
    return await modal.present();
  }
  // 编辑更多
  async openModalMoreEditInfo(item, nextStep?) {
    if (item.subData) {
      item['subHtmlObj'] = item.subData;
    }
    if (item.type) {
      item['formType'] = item.type;
      if (item['subHtmlObj'] && item['subHtmlObj'].length > 0) {
        item['subHtmlObj'].forEach(element => {
          if (element.type) {
            element['formType'] = element.type;

          }
          if (element.value === undefined) {
            element.value = '';
          }
        });
      }

    }
    const that = this;
    const modal = await this.modalCtrl.create({
      component: ModalOfEditMoreInfoComponent,
      componentProps: { value: item, nextStep, allForm: this.formGroup, showSearchModal: item.showSearchModal ? 1 : 0 },
      id: item.showSearchModal ? 'showSearchModal' : ''
    });
    modal.onDidDismiss().then(function (data) {
      if (data.data && data.data.form) {
        const hiddenForm: FormGroup = data.data.form;
        for (const cons in hiddenForm.controls) {
          that.formGroup.patchValue({ [cons]: hiddenForm.controls[cons].value });
        }
        if (item.formType === 'modalOfMoreItems') {
          if (item.subHtmlObj && item.showIndex < item.subHtmlObj.length) {
            // 优先展示showValue
            if (item.subHtmlObj[item.showIndex].showValue) {
              item.showValue = item.subHtmlObj[item.showIndex].showValue;
            } else {
              item.showValue = hiddenForm.controls[item.subHtmlObj[item.showIndex].formKey].value;
            }
          } else if (item.subHtmlObj) {
            if (item.subHtmlObj[0].showValue) {
              item.showValue = item.subHtmlObj[0].showValue;
            } else {
              item.showValue = hiddenForm.controls[item.subHtmlObj[0].formKey].value;
            }
          }
        }
      }
    });
    return await modal.present();
  }
  async openModalDepartmentPage(item) {
    const modal = await this.modalCtrl.create({
      component: ChooseDepartmentComponent,
      componentProps: { tagData: item.link, modalTitle: "选择部门", backValue: true }
    });
    modal.onDidDismiss().then((data) => {

      if (data.data) {

        this.formGroup.patchValue({ [item.formKey]: data.data.code });
        item.showValue = data.data.name;
      }
    });
    return await modal.present();
  }
  search(event?) {
    const that = this;
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      that.searchEvent(event);
    }, 300);
  }

  // 打开城市选择
  async openModalCityPage(item) {
    const that = this;
    const modal = await this.modalCtrl.create({
      component: ChooseCityComponent,
      componentProps: { value: item.link.target, modalTitle: '选择地址', noStorage: true ,link:item.link}
    });
    modal.onDidDismiss().then(function (data) {
      const value = data.data;
      if (value !== undefined && value.n !== undefined) {
        item.showValue = value.n;
        item.value = value.i;
        that.formGroup.patchValue({ [item.formKey]: value.i });
        that.getAreaData(value.i);
      }
    });
    return await modal.present();
  }

  getAreaData(code) {
    this.data.data.formObj.forEach(element => {
      if (element.formKey && (element.formKey.indexOf('district_id') > -1 || element.formKey.indexOf('area_code') > -1 || element.formKey.indexOf('expect_district') > -1) ) {
        const table = {
          code
        };
        const params = {
          content: table,
          id: element.id ? element.id : (element.submit ? element.submit.id : ''),
          sessionId: localStorage.getItem('sessionId')
        };
        element.value = '';
        element.showValue = '';
        // 请求获取新数据
        this.http.post('application/submit', params, res => {
          // 请求数据成功
          if (res.data.items) {
            element.data = res.data.items;
            this.getPickerLabel(element);
          } else if (res.data.data) {
            element.data = res.data.data;
            this.getPickerLabel(element);
          }
            else {
            // 请求数据失败
            this.appGlobalService.showToast(res.message, 2000, 'middle');
            this.getPickerLabel(element);
          }
        });
      }
    });


  }
  doDiss() {
    this.modalCtrl.dismiss();
  }
  getDate(max, item) {
    if (item.max === max) {
      /* console.log(item.max)
      console.log(max) */
      return item.maxDate = item.maxDate ? item.maxDate : this.getDateTime(max);
    } else if (item.min === max) {
      /*  console.log(item.max)
       console.log(max) */
      return item.minDate = item.mimDate ? item.minDate : this.getDateTime(max);
    }
  }
  datetime(result: Date, item) {
    item.value = this.currentDateFormat(result, 'yyyy-mm-dd');
    item.defValue = result;
    item.defValueone = result;
    this.tagData.data.data.formObj.forEach(element => {
      if (element.type === "dateInput") {
        if (element.itemList[0].value) {
          element.itemList[1].disable = false;
        }
      }
    });
  }
  contrast(firstDate, lastDate) {
    const arr = firstDate.split("-");
    const firsttime = new Date(arr[0], arr[1], arr[2]);
    const firsttimes = firsttime.getTime();

    const arrs = lastDate.split("-");
    const lasttime = new Date(arrs[0], arrs[1], arrs[2]);
    const lasttimes = lasttime.getTime();
    if (firsttimes >= lasttimes) {
      return false;
    } else {
      return true;
    }
  }
  formatIt(date: Date, form: string) {
    const pad = (n: number) => (n < 10 ? `0${n}` : n);
    const dateStr = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
    const timeStr = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
    if (form === 'YYYY-MM-DD') {
      return dateStr;
    }
    if (form === 'HH:mm') {
      return timeStr;
    }
    return `${dateStr} ${timeStr}`;
  }
  getDateTime(date) {
    if (!date) {
      return;
    }
    if (date.indexOf(' ') > -1) {
      // console.log(new Date(Date.parse(date.replace(/-/g, "/"))));
      return new Date(Date.parse(date.replace(/-/g, "/")));
    } else {
      // console.log(new Date(Date.parse((date + ' ' + '23:59:59').replace(/-/g, "/"))));
      return new Date(Date.parse((date + ' ' + '23:59:59').replace(/-/g, "/")));
    }
  }
  currentValue(item) {
    if (!item.value || item.value === '') {
      return item.placeHolder;
    } else {
      return item.value;
    }
  }
  // 时间段选择
  currentDateFormat(date, format: string = 'HH:MM'): any {
    const pad = (n: number): string => (n < 10 ? `0${n}` : n.toString());
    return format
      .replace('yyyy', date.getFullYear())
      .replace('mm', pad(date.getMonth() + 1))
      .replace('dd', pad(date.getDate()))
      .replace('HH', pad(date.getHours()))
      .replace('MM', pad(date.getMinutes()))
      .replace('ss', pad(date.getSeconds()));
  }

  // 打开行业模态框 // 多选全国区域
  async modalMultipleFormKeySelect(item) {
    const that = this;
    // 初始化参数：
    item.roomType = this.roomType;
    item.roomHall = this.roomHall;
    item.roomBit = this.roomBit;
    const modal = await this.modalCtrl.create({
      showBackdrop: true,
      cssClass: "house-type",
      component: PublishHouseTypeComponent,
      componentProps: { tagData: item }
    });
    modal.onDidDismiss().then((modalData) => {
      if (modalData && modalData.data) {
        this.formGroup.patchValue({ [item.formKey]: modalData.data.itemdata.roomType.value });
        this.formGroup.patchValue({ [item.subData[0].formKey]: modalData.data.itemdata.roomHall.value });
        this.formGroup.patchValue({ [item.subData[1].formKey]: modalData.data.itemdata.roomBit.value });
        this.roomType = modalData.data.itemdata.roomType.value;
        this.roomHall = modalData.data.itemdata.roomHall.value;
        this.roomBit = modalData.data.itemdata.roomBit.value;
        this.houseTypeShowValue =
          modalData.data.itemdata.roomType.label +
          modalData.data.itemdata.roomHall.label +
          modalData.data.itemdata.roomBit.label;
      }
    });
    return await modal.present();
  }


  async closeModal() {
    if (this.tagData.data.name !== 'appFormTag') {
      // this.appGlobalService.goBack();
      this.appGlobalService.goBack();
      this.appGlobalService.popTarget();
    } else {
      const modal = await this.modalCtrl.getTop();
      if (modal) {
        modal.dismiss({ form: this.formGroup });
      }
    }

  }

  // 左边大类点击
  itemLeftClick(it, item) {
    item.children.forEach(element => {
      element.open = false;
    });
    it.open = true;
    item.current = it;
    this.formGroup.patchValue({ [item.formKey]: it.code.toString() });
  }

  chooseAll(it, item) {
    it.checked = !it.checked;

    if (it.checked) {
      if (item.current) {
        item.current.hasValue = true;
      }

      if (typeof item.value === 'string') {
        item.value = item.value.split(',');
      }
      item.value.push(it.value);
      // 加入大类 清除小类
      it.children.forEach(element => {
        element.checked = true;
        const index = item.value.findIndex(v => (v === element.value));
        if (index > -1) {
          item.value.splice(index, 1);
        }
      });

      this.checkBigVaue(item);
    } else {
      if (item.current) {
        item.current.hasValue = false;
      }
      it.children.forEach(element => {
        element.checked = false;
        //  清除 大类、小类
        const index = item.value.findIndex(v => (v === element.value) || it.value === v);
        if (index > -1) {
          item.value.splice(index, 1);
        }
      });

    }
    this.checkBigVaue(item);
    console.log(item.value);
    // if (!this.formGroup.value[item.formKey]) {
    this.formGroup.patchValue({ [item.formKey]: item.value.toString() });
    // }
    $('#' + it.value).slideToggle("slow");

  }

  checkBigVaue(item) {
    // 遍历当前二级分类是否全选
    if (item.current) {
      let n = 0;
      item.current.children.forEach(element => {
        element.checked ? ++n : '';
      });
      // 全选择 清除 二三级
      if (item.current.children.length === n) {
        item.current.checked = true;
        item.value.push(item.current.value);
        // 清除 二级
        item.current.children.forEach(element => {

          const index = item.value.findIndex(v => (v === element.value));
          if (index > -1) {
            item.value.splice(index, 1);
          }
          // 清除 三级
          this.removeValue(item, element);
        });
      } else {
        item.current.checked = false;
        // 清除一级分类value
        const index = item.value.findIndex(v => (v === item.current.value));
        if (index > -1) {
          item.value.splice(index, 1);
        }
        // 遍历 二 三级
        item.current.children.forEach(element => {
          if (element.checked) {
            if (item.value.findIndex(v => (v === element.value)) === -1) {
              item.value.push(element.value);
            }

          } else {
            element.children.forEach(e => {
              if (e.checked && item.value.findIndex(v => (v === e.value)) === -1) {
                item.value.push(e.value);
              }
            });
          }

        });
      }
    }
  }


  tagClick(tag, it, item) {
    tag.checked = !tag.checked;
    let i = 0;
    it.children.forEach(element => {
      element.checked ? ++i : '';
    });
    i === it.children.length ? it.checked = true : it.checked = false;
    if (it.checked) {
      if (item.current) {
        item.current.hasValue = true;
      }
      if (typeof item.value === 'string') {
        item.value = item.value.split(',');
      }
      // 加入大类 清除小类
      item.value.push(it.value);
      it.children.forEach(element => {

        const index = item.value.findIndex(v => (v === element.value));
        if (index > -1) {
          item.value.splice(index, 1);
        }

      });
    } else {
      it.children.forEach(element => {
        // 先清除
        if (item.current) {
          item.current.hasValue = false;
        }
        const index = item.value.findIndex(v => (v === element.value || v === it.value));
        if (index > -1) {
          item.value.splice(index, 1);
        }

      });

      // 再加入
      it.children.forEach(element => {
        if (element.checked) {
          if (item.current) {
            item.current.hasValue = true;
          }
          item.value.push(element.value);
        }
      });
    }
    this.checkBigVaue(item);
    console.log(item.value);
    this.formGroup.patchValue({ [item.formKey]: item.value.toString() });
  }

  removeValue(item, it) {
    it.children.forEach(e => {
      const index = item.value.findIndex(v => (v === e.value));
      if (index > -1) {
        item.value.splice(index, 1);

      }
    });
  }
  addValue(item, it) {
    it.children.forEach(e => {
      if (e.checked && item.value.findIndex(v => (v === e.value)) === -1) {
        item.value.push(e.value);
      }
    });
  }

  clearCheckBtn(data) {
    data.forEach(element => {
      element.checked = false;
      element.hasValue = false;
      if (element.children) {
        this.clearCheckBtn(element.children);
      }
    });
  }

  async modalMultipleSelect3(item, auto?, canChooseSecond?) {

    const that = this;
    if (item.type) {
      item['formType'] = item.type;
      if (item.type === 'switchButtonFW_3') {

      } else {
        if (!item.children || item.children.length === 0) {
          if (item.tips && item.tips.length > 0) {
            this.appGlobalService.showToast(item.tips, 1500, "middle");
          }
          return;
        }
      }
    }
    if (auto) {
      item['auto'] = auto;
    }
    if (canChooseSecond) {
      item['canChooseSecond'] = (canChooseSecond !== undefined) ? canChooseSecond : true;
    }
    const modal = await this.modalCtrl.create({
      component: ModalMultipleSelect3Component,
      componentProps: { value: item },
      cssClass: 'auto-modal',

    });
    modal.onDidDismiss().then(function (data) {
      if (item.type === 'switchButtonFW_3') {
        Object.assign(item, data.data)
        that.formGroup.patchValue({ [item.formKey]: item.value });

      } else if (data.data) {
        const selectedData = data.data;
        const selectedLabel = selectedData.map(v => {
          return v.label;
        });
        const selectedValue = selectedData.map(v => {
          return v.code;
        });
        if (data.data.length) {
          item.value = selectedValue.join(',');
          item.showValue = selectedLabel.join(',');
          that.formGroup.patchValue({ [item.formKey]: item.value });

        } else {
          that.formGroup.patchValue({ [item.formKey]: '' });
          item.value = '';
        }
      }
    });
    return await modal.present();
  }

  // singleColumnSelect
  showActionSheet(item) {
    if (item.disabled) {
      if (item.tips && item.tips.length > 0) {
        this.appGlobalService.showToast(item.tips, 1500, "middle");
      }
      return;
    }
    {
      const that = this;
      let lastIndex: -1;
      const buttons: any = [];
      item.data.forEach((element, index) => {
        buttons.push(element.label);
        if (element.value === item.value) {
          lastIndex = index;
        }
      });
      // 上次选择过
      if (lastIndex > -1) {
        ActionSheetService.showActionSheetWithOptions(
          {
            options: buttons,
            // cancelButtonIndex: BUTTONS.length - 1,
            destructiveButtonIndex: lastIndex,
            // title: 'title',
            // message: item.label,
            maskClosable: true
          },
          buttonIndex => {
            if (buttonIndex > -1) {
              console.log(item.data[buttonIndex]);
              that.selectItem(buttonIndex, item);
            }
          }
        );
      } else {
        // 第一次选择
        ActionSheetService.showActionSheetWithOptions(
          {
            options: buttons,
            maskClosable: true
          },
          buttonIndex => {
            if (buttonIndex > -1) {
              console.log(item.data[buttonIndex]);
              that.selectItem(buttonIndex, item);
            }
          }
        );
      }
    }

  }

  selectItem(index, item) {
    this.formGroup.patchValue({ [item.formKey]: item.data[index].value });
    item.showValue = item.data[index].label;
    item.value = item.data[index].value;

  }
}



